package Set集合;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class hashSet集合不重复的原因  {
    public static void main(String[] args) {

        Set<Apple> list = new HashSet<>();

//        无序：不是按照插入的顺序排序
//        默认情况下：内容相同，地址不同判定为不同对象
//        重写hashCode方法和equals方法后，内容相同，地址不同判定为重复对象
        Apple apple1 = new Apple("红富士",23,"红色");
        Apple apple2 = new Apple("红富士",23,"红色");
        Apple apple3 = new Apple("绿元帅",45,"青色");

        list.add(apple1);
        list.add(apple2);
        list.add(apple3);

        System.out.println(list);

    }
}

class Apple {
    private String name ;
    private int price ;
    private String color ;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Apple apple = (Apple) o;
        return price == apple.price &&
                Objects.equals(name, apple.name) &&
                Objects.equals(color, apple.color);
    }

    @Override
    public int hashCode() {
//        计算哈希值
//        输入对象的各个参数，对象内容相同则按重复处理
        return Objects.hash(name, price, color);
    }

    public Apple() {
    }

    public Apple(String name, int price, String color) {
        this.name = name;
        this.price = price;
        this.color = color;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return price
     */
    public int getPrice() {
        return price;
    }

    /**
     * 设置
     * @param price
     */
    public void setPrice(int price) {
        this.price = price;
    }

    /**
     * 获取
     * @return color
     */
    public String getColor() {
        return color;
    }

    /**
     * 设置
     * @param color
     */
    public void setColor(String color) {
        this.color = color;
    }

    public String toString() {
        return "Apple{name = " + name + ", price = " + price + ", color = " + color + "}";
    }
}
